package com.xiaohua.api.utils.security;

import java.util.Random;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * API凭证相关工具类
 *
 * @author 小花
 * @date 2025-04-03
 */
public class ApiCredentialUtils {
    
    private static final Logger log = LoggerFactory.getLogger(ApiCredentialUtils.class);
    
    /**
     * 生成随机API密钥
     * 
     * @param length 密钥长度
     * @return 随机密钥
     */
    public static String generateApiKey(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        
        return sb.toString();
    }
    
    /**
     * 生成随机API密钥对
     * 
     * @return 密钥对数组 [apiKey, apiSecret]
     */
    public static String[] generateApiKeyPair() {
        String apiKey = generateApiKey(16);
        String apiSecret = generateApiKey(32);
        
        return new String[] { apiKey, apiSecret };
    }
    
    /**
     * 对敏感信息进行掩码处理
     * 
     * @param input 输入字符串
     * @param showLength 显示的字符数
     * @return 掩码后的字符串
     */
    public static String maskSensitiveInfo(String input, int showLength) {
        if (input == null || input.isEmpty() || input.length() <= showLength) {
            return "***";
        }
        
        return input.substring(0, showLength) + "**********";
    }
    
    /**
     * 计算字符串的SHA-256哈希值
     * 
     * @param input 输入字符串
     * @return 哈希值的Base64编码结果
     */
    public static String sha256Hash(String input) {
        if (input == null || input.isEmpty()) {
            return null;
        }
        
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes());
            return Base64.getEncoder().encodeToString(hash);
        } catch (NoSuchAlgorithmException e) {
            log.error("计算SHA-256哈希值失败", e);
            return null;
        }
    }
    
    /**
     * 计算HMAC签名
     * 
     * @param data 待签名数据
     * @param apiSecret 密钥
     * @return 签名结果
     */
    public static String calculateHmacSignature(String data, String apiSecret) {
        if (data == null || data.isEmpty() || apiSecret == null || apiSecret.isEmpty()) {
            return null;
        }
        
        try {
            javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256");
            javax.crypto.spec.SecretKeySpec secretKeySpec = new javax.crypto.spec.SecretKeySpec(apiSecret.getBytes(), "HmacSHA256");
            mac.init(secretKeySpec);
            byte[] hmacData = mac.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(hmacData);
        } catch (Exception e) {
            log.error("计算HMAC签名失败", e);
            return null;
        }
    }
    
    /**
     * 验证API签名
     * 
     * @param signature 签名
     * @param data 原始数据
     * @param apiSecret 密钥
     * @return 验证是否通过
     */
    public static boolean verifySignature(String signature, String data, String apiSecret) {
        if (signature == null || signature.isEmpty()) {
            return false;
        }
        
        String calculatedSignature = calculateHmacSignature(data, apiSecret);
        return signature.equals(calculatedSignature);
    }
} 